//
//  PrinterSearchView.m
//  IOS_SDK
//
//  Created by HaiJiao Chen on 12-12-30.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "PrinterSearchView.h"
#import "StarIO/SMPort.h"
#import "AppDelegate.h"

@implementation PrinterSearchView
@synthesize name_label;

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self)
    {
        printerArray = [SMPort searchPrinter];
    }
    return self;
}

- (void)dealloc
{
    [printerArray release];
    [super dealloc];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return printerArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }
    
    if (indexPath.row < printerArray.count) {
        PortInfo *port = [printerArray objectAtIndex:indexPath.row];
        cell.textLabel.text = port.modelName;
        NSString *detailText = [NSString stringWithFormat:@"%@(%@)", port.portName, port.macAddress];
        cell.detailTextLabel.text = detailText;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row < printerArray.count) {
        PortInfo *portInfo = [printerArray objectAtIndex:indexPath.row];
        [AppDelegate setPortName:portInfo.portName];
        
        NSString *localPortSettings = @"mini";
        
        [AppDelegate setPortSettings:localPortSettings];
        
        name_label.text = portInfo.portName;
    }
    
    [self removeFromSuperview];
}

@end
